<?php
//dezend by http://www.yunlu99.com/ QQ:270656184
defined('BASEPATH') || exit('No direct script access allowed');
class Channels extends MY_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->verify_user();
	}

	public function index()
	{
		$coin_id = intval($this->input->get('cid'));

		if ($coin_id) {
			$coin = $this->d->find(array('table' => 'coin', 'where' => 'id=' . $coin_id . ' and status=1'));
		}
		else {
			$coin = $this->d->find(array('table' => 'coin', 'where' => 'status=1', 'order' => 'sort asc'));
		}

		if (!$coin) {
			error404();
		}

		$where['user_id'] = $this->user['id'];
		$where['coin_id'] = $coin['id'];
		$result = $this->result_list(array('table' => 'address', 'where' => $where, 'url' => 'channels/index', 'order' => 'add_time desc', 'per_page' => 10));
		$d['page'] = $result['page'];
		$list = $result['list'];

		foreach ($list as $k => $v) {
			$list[$k]['coin'] = $this->d->find(array('table' => 'coin', 'where' => 'id=' . $v['coin_id']));
		}

		$d['list'] = $list;
		$d['coin'] = $coin;
		$d['coins'] = $this->d->rows(array('table' => 'coin', 'where' => 'status=1', 'order' => 'sort asc'));
		$this->show(array('header', 'user_left', 'channels', 'footer'), $d);
	}

	public function address()
	{
		$coin_id = intval($this->uri->segment(3));

		if (!$coin_id) {
			exit('找不到币种');
		}

		$d['coin'] = $this->db->where('id', $coin_id)->get('coin')->row_array();

		if (!$d['coin']) {
			exit('找不到币种');
		}

		$this->show(array('channels_address'), $d);
	}

	public function address_del()
	{
		$id = intval($this->input->post('id'));

		if ($id <= 0) {
			ajax_return(1, '找不到要目标记录');
		}

		$address = $this->db->where('id', $id)->where('user_id', $this->user['id'])->get('address')->row_array();

		if (!$address) {
			ajax_return(1, '找不到要目标记录');
		}

		$log_count = $this->db->where('address_id', $id)->where('user_id', $this->user['id'])->count_all_results('draw_coin');

		if (0 < $log_count) {
			ajax_return(1, '该账户有使用记录，不能删除');
		}

		if ($this->db->where('id', $id)->delete('address')) {
			ajax_return(0, '删除成功');
		}
		else {
			ajax_return(1, '删除失败');
		}
	}

	public function address_insert()
	{
		$paypwd = $this->input->post('paypwd');
		if (!$paypwd || !$this->pwd->verify($paypwd, $this->user['paypwd'])) {
			ajax_return(1, '安全密码错误');
		}

		$coin_id = $this->input->post('coin_id');
		$coin_id = intval($this->input->post('coin_id'));

		if (!$coin_id) {
			ajax_return(1, '找不到币种');
		}

		$coin = $this->d->find(array('table' => 'coin', 'where' => 'id=' . $coin_id));

		if (!$coin) {
			ajax_return(1, '找不到币种');
		}

		$code = $this->input->post('code');

		if (!$code) {
			ajax_return(1, '钱包地址不能为空');
		}

		$d['coin_id'] = $coin_id;
		$d['code'] = $code;
		$d['user_id'] = $this->user['id'];
		$d['add_time'] = time();

		if ($this->db->insert('address', $d)) {
			ajax_return(0, '添加成功');
		}
		else {
			ajax_return(1, '添加失败');
		}
	}
}

?>
